import { defineStore } from "pinia";
import type { loginResponseData, formData } from "@/api/user/type";
import { reqLogin, reqLogout } from "@/api/user";
import { GET_TOKEN, REMOVE_TOKEN, SET_TOKEN } from "@/utils/token";
import { ref } from 'vue'
export const useUserStore = defineStore('user', () => {
    const token = ref<string>(GET_TOKEN() as string)
    const username = ref<string>('')
    const userLogin = async (data: formData) => {
        const res: loginResponseData = await reqLogin(data)
        if (res.data) {
            token.value = res.data.token
            username.value = res.data.username
            SET_TOKEN(token.value)
            return 'ok'
        } else {
            return Promise.reject(new Error(res.data))
        }
    }
    const userLogout = async () => {
        const res: any = await reqLogout(username.value)
        if (res.success) {
            token.value = ''
            username.value = ''
            REMOVE_TOKEN()
            return 'ok'
        } else {
            return Promise.reject(new Error(res.message))
        }
    }
    return { token, username, userLogin, userLogout }
})